<?php
require_once('pinyin_table_utf8.php');

class mypinyin{
	/**
 	* @param $string 编码为gb2312的中文句子
 	* 返回一段话的所有可能的拼音
 	* 注意返回值为gb2312
	 * */
	private   static  function get_pinyin_array($string)
	{
		global $pinyin_table;
		$flow = array();
		for ($i=0;$i<strlen($string);$i++)
		{
			if (ord($string[$i]) >= 0x81 and ord($string[$i]) <= 0xfe)
			{
				$h = ord($string[$i]);
				if (isset($string[$i+1]))
				{
					$i++;
					$l = ord($string[$i]);
					if (isset($pinyin_table[$h][$l]))
					{
						array_push($flow,$pinyin_table[$h][$l]);
					}
					else
					{
						array_push($flow,$h);
						array_push($flow,$l);
					}
				}
				else
				{
					array_push($flow,ord($string[$i]));
				}
			}
			else
			{
				array_push($flow,ord($string[$i]));
			}
		}

		//print_r($flow);

		$pinyin = array();
		$pinyin[0] = '';
		for ($i=0;$i<sizeof($flow);$i++)
		{
			if (is_array($flow[$i]))
			{
				if (sizeof($flow[$i]) == 1)
				{
					foreach ($pinyin as $key => $value)
					{
						$pinyin[$key] .= "_".$flow[$i][0]."_";
					}
				}
				if (sizeof($flow[$i]) > 1)
				{
					$tmp1 = $pinyin;
					foreach ($pinyin as $key => $value)
					{
						$pinyin[$key] .= "_".$flow[$i][0]."_";
					}
					for ($j=1;$j<sizeof($flow[$i]);$j++)
					{
						$tmp2 = $tmp1;
						for ($k=0;$k<sizeof($tmp2);$k++)
						{
							$tmp2[$k] .= "_".$flow[$i][$j]."_";
						}
						array_splice($pinyin,sizeof($pinyin),0,$tmp2);
					}
				}
			}
			else
			{
				foreach ($pinyin as $key => $value)
				{
					$pinyin[$key] .= chr($flow[$i]);
				}
			}
		}
		return $pinyin;
	}

	/**
 	* 输入UTF8字符串，得到UTF8的拼音
 	* @param $utf8String utf8类型的字符串
 	* */
	public  static  function get_utf8_pinyin($utf8String){
		$text = mb_convert_encoding($utf8String,"gb2312","utf-8");
		$flow = self::get_pinyin_array($text);
		$num = count($flow);
		$utf8Result = array();
		for($i = 0; $i< $num;$i++)	{
			$utf8Result[] =  mb_convert_encoding($flow[$i],"utf-8","gb2312");
		}
		return $utf8Result;
	}

}

//注意，需要先转化为gb2312才能调用该函数
//$text = mb_convert_encoding("看看多音字的情况，比如：还、乐。","gb2312","utf-8");
//$text = mb_convert_encoding("乐","gb2312","utf-8");
//$flow = get_pinyin_array($text);

/*$utf8pinyin = get_utf8_pinyin("看看多音字的情况，比如：还、乐。");
print_r($utf8pinyin);

$utf8pinyin = get_utf8_pinyin("乐");
print_r($utf8pinyin);

*/



?>